package com.kcloud.commons.authorization.mp.parser;

import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.core.parser.SqlInfo;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.TableNameParser;
import com.baomidou.mybatisplus.extension.parsers.ITableNameHandler;
import lombok.Data;
import lombok.experimental.Accessors;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Collection;

/**
 * 权限表名动态解析
 * @author songhuiqing
 */
@Data
@Accessors(chain = true)
public class AuthorizationTableNameParser implements ISqlParser {

    private ITableNameHandler tableNameHandler;

    @Override
    public SqlInfo parser(MetaObject metaObject, String sql) {
        Assert.isFalse(tableNameHandler == null, "tableNameHandler is empty.");
        Collection<String> tables = new TableNameParser(sql).tables();
        if (CollectionUtils.isNotEmpty(tables)) {
            boolean sqlParsed = false;
            String parsedSql = sql;
            for (final String table : tables) {
                if (null != tableNameHandler) {
                    parsedSql = tableNameHandler.process(metaObject, parsedSql, table);
                    sqlParsed = true;
                }
            }
            if (sqlParsed) {
                return SqlInfo.newInstance().setSql(parsedSql);
            }
        }
        return null;
    }
}
